package com.shujia.scala

import java.sql.{Connection, DriverManager, PreparedStatement}
import scala.io.Source

object Demo8JDBC {
  def main(args: Array[String]): Unit = {
    //1、加载驱动
    Class.forName("com.mysql.jdbc.Driver")
    //2、创建数据库连接
    val con: Connection = DriverManager.getConnection("jdbc:mysql://master:3306/bigdata31", "root", "123456")

    //3、读取文件
    val students: Iterator[String] = Source.fromFile("data/students.txt").getLines()
    //4、循环写入数据
    for (student <- students) {
      //解析数据
      val split: Array[String] = student.split(",")
      val id: Long = split(0).toLong
      val name: String = split(1)
      val age: Long = split(2).toLong
      val gender: String = split(3)
      val clazz: String = split(4)
      //5、编写sql插入数据
      val stat: PreparedStatement = con.prepareStatement("insert into students values(?,?,?,?,?)")
      stat.setLong(1, id)
      stat.setString(2, name)
      stat.setLong(3, age)
      stat.setString(4, gender)
      stat.setString(5, clazz)
      //执行sql
      stat.execute()
    }
    con.close()
  }
}
